import Solution.TreeNode;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {

    /*自顶向下 */
    public void flatten(TreeNode root) {
        while (root != null){
            if (root.left == null){
                root = root.right;
            } else {
                TreeNode pre = root.left;
                while (pre.right != null){
                    pre = pre.right;
                }
                // 右子树放到左子树的最右节点
                pre.right = root.right;
                // 左子树插到右子树
                root.right = root.left;
                root.left = null;
                // 下一个节点
                root = root.right;
            }
        }
    }

    private TreeNode pre = null;

    /*自底向上 */
    public void flatten_recur(TreeNode root){
        if (root == null) return;
        flatten(root.right);
        flatten(root.left);
        root.right = pre;
        root.left = null;
        pre = root;
    }
}